package org.txazo.stat.web.listener;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Web启动监听
 * 
 * @author Tu XiaoZhou
 * @since 2013-04-12
 * 
 */
public class ApplicationStartupListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		System.clearProperty("log4j.log.path");
		System.clearProperty("edition");
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		String path = servletContextEvent.getServletContext().getRealPath("/");
		path = path.replace('\\', '/').replace("/webapps/htdocs", "");
		System.setProperty("log4j.log.path", path);

		ServletContext context = servletContextEvent.getServletContext();
		initEdition(context);
	}

	private void initEdition(ServletContext context) {
		String edition = null;
		InputStream in = context
				.getResourceAsStream("/WEB-INF/classes/edition.properties");
		Properties prop = new Properties();
		if (in != null) {
			try {
				prop.load(in);
			} catch (IOException e) {
				e.printStackTrace();
			}
			edition = prop.getProperty("edition");
		}

		context.setAttribute("edition", edition);
	}

}
